package com.chain.BrotherExchange.im.ui;

import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;


import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.im.model.Message;

import java.util.ArrayList;
import java.util.List;

public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {

    private final RecyclerView mRecyclerView;
    private List<Message> mMessageList = new ArrayList<>();

    MessageAdapter(RecyclerView recyclerView){
        this.mRecyclerView = recyclerView;
    }

    @NonNull
    @Override
    public MessageAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new ViewHolder(LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.item_message, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MessageAdapter.ViewHolder holder, int position) {
        Message message = mMessageList.get(position);
        holder.mMessageTextView.setText(message.getMessage());

        if (message.getType() == Message.SEND_TYPE) {
            holder.mMessageTextView.setTextColor(Color.WHITE);
            holder.mMessageTextView.setBackgroundResource(R.mipmap.mq_bg_msg_right);
            ((FrameLayout.LayoutParams) holder.mMessageTextView.getLayoutParams()).gravity = Gravity.END;
        } else {
            holder.mMessageTextView.setTextColor(Color.BLACK);
            holder.mMessageTextView.setBackgroundResource(R.mipmap.mq_bg_msg_left);
            ((FrameLayout.LayoutParams) holder.mMessageTextView.getLayoutParams()).gravity = Gravity.START;
        }
    }

    void addMessage(Message message) {
        mMessageList.add(message);
        notifyDataSetChanged();
        mRecyclerView.smoothScrollToPosition(mMessageList.size());
    }

    void addMessageList(List<Message> messageList){
        mMessageList.addAll(messageList);
        notifyDataSetChanged();
        mRecyclerView.smoothScrollToPosition(mMessageList.size());
    }

    @Override
    public int getItemCount() {
        return mMessageList.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        private final TextView mMessageTextView;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            mMessageTextView = itemView.findViewById(R.id.message_text);
        }
    }
}
